package com.nine.pesys.model.action;

import com.nine.pesys.base.BaseAction;
import com.nine.pesys.model.entity.Role;
import com.nine.pesys.model.entity.User;
import com.nine.pesys.util.annotation.Privilege;
import com.nine.pesys.util.common.CommomUtils;
import com.nine.pesys.util.common.PageData;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 *
 * Created by L先森 on 2014/12/23.
 */
@Controller
@Scope("prototype")
@Namespace("/user")
@ParentPackage(value="my_struts")
@Results({
        @Result(name = "register",location = "/front/home.jsp"),
        @Result(name = "login",location = "/front/home.jsp"),
        @Result(name = "fail",location = "/error.jsp"),
        @Result(name = "loginFail",location = "/front/login.jsp"),
        @Result(name = "input",location = "/front/Register.jsp"),
        @Result(name = "setThePrivilege",location = "/front/home.jsp"),
        @Result(name = "loginOut", type = "redirectAction", location = "/index.do"),


        @Result(name = "bsSubmit",type = "redirectAction",location = "/userList.do"),
        @Result(name = "bsSubmitFail",location = "/admin/house_edit.jsp"),
        @Result(name = "bsLogin",location = "/admin/index.jsp"),
        @Result(name = "bsLoginFail",location = "/admin/login.jsp"),
        @Result(name = "bsLoginOut",location = "/admin/login.jsp"),
        @Result(name = "bsuserList",location = "/admin/house_list.jsp"),
        @Result(name = "bsDel", type = "redirectAction",location = "/userList.do"),
        @Result(name = "bsEditUser",location = "/admin/house_edit.jsp"),
})
@Privilege
public class UserAction extends BaseAction<User>{
    private String isAutoLogin;
    private String securityCode;
    private String privilegeName;
    private Long userId;
    private String allIDCheck;
    private String roleName;
 //    注册
    @Action(value = "/register")
    public String register() throws Exception{
//        接受数据
//        每个注册的账号都是普通用户
        Role  role = new Role();
        if (roleName==null||roleName.equals("")){
            role = this.roleService.getById(1L);
        }else {
            role = new Role();
            role.setName(roleName);
            roles =  this.roleService.getByCondition(role);
            if (roles==null||roles.size()<=0&&isBS!=null){
                ActionContext.getContext().put("message","对不起，系统不存在该权限");
                return "bsSubmitFail";
            }
            role = roles.get(0);
        }
        roles.add(role);
        Set<Role> roles1 = new HashSet<Role>(roles);
        model.setRoles(roles1);
        model.setPassword(CommomUtils.mBase64Encode(model.getPassword()));
//        以免两边有刻空格
        model.setStuNumber(model.getStuNumber().trim());
        System.out.println(model.getStuNumber());
        User user = this.userService.getByStuNum(model.getStuNumber());
        if (user!=null&&isBS!=null){
            ActionContext.getContext().put("message"," 对不起该用户已存在");
            return "bsSubmitFail";
        }
        userService.save(model);
        if(isBS!=null)
            return "bsSubmit";
        return "register";
    }

//    登陆(用学生证登陆)
    @Action(value = "/login")
    @SkipValidation
    public String login() throws Exception{
        String serverSecurityCode = (String)session.get("SESSION_SECURITY_CODE");
        if(!serverSecurityCode.equals(securityCode)){
            ActionContext.getContext().put("message","验证码错误");
            if(isBS!=null)
                    return  "bsLoginFail";
            return "loginFail";
        }
        model.setPassword(CommomUtils.mBase64Encode(model.getPassword()));
        users = this.userService.getByCondition(model);
        if(users.size()>0){
            User user = users.get(0);
            this.session.put("user", user);
            System.out.println(isAutoLogin+"=================");
            if(isAutoLogin!=null){
                 HttpServletResponse response = ServletActionContext.getResponse();
                 CommomUtils.addCookie(user.getStuNumber()+"_"+user.getPassword(),"loginInfo",response);
            }
            if(isBS!=null)
                return "bsLogin";
            return "login";
        }
        ActionContext.getContext().put("message","用户不存在或者密码错误");
        if(isBS!=null)
            return  "bsLoginFail";
        return "loginFail";
    }

    /**
     * 当用户忘了密码或者要修改密码的时候(都要提供这个信息)
     * 这里需要用户提供stuNumber和email
     * @return
     * @throws Exception
     */
    @Action("/updatePassword")
    @SkipValidation
    public String updatePassword() throws Exception{
        String stuNumber = model.getStuNumber();
        String email = model.getEmail();
        String password = model.getPassword();
        List<User> users = this.userService.getByCondition(model);
        User user = users.get(0);
        if(user!=null){
            user.setPassword(CommomUtils.mBase64Encode(password));
            this.userService.update(user);
            return "rePassword";
        }
        return "fail";
    }

//    注销
    @Action("/loginOut")
    @SkipValidation
    public String loginOut() throws Exception{
//        清空session和cookie
        this.session.remove("user");
        System.out.println("============44444444===============");
        HttpServletResponse response = ServletActionContext.getResponse();
        CommomUtils.delCookie(response,"loginInfo");
        if (isBS!=null)
            return "bsLoginOut";
        return "loginOut";
    }


    /**
     *     设置用户权限(只能是超级用户才能设置)
            若选择为空，这是删除该用户设置过的权限，还原为common，相当于删除权限
     */
        @Privilege("super")
        public String setThePrivilege() throws Exception{
//            接受要设置的用户Id和要设置的权限是什么
            User user = this.userService.getById(userId);
            Role role = this.roleService.getByName(privilegeName).get(0);
            roles.add(role);
            Set<Role> roles1 = new HashSet<Role>(roles);
            user.setRoles(roles1);
            this.userService.update(user);
            return "setThePrivilege";
        }

    @Action("/userList")
    @Privilege("system")
    @SkipValidation
    public String userList() throws Exception{
        users = this.userService.findAll();
        if (users!=null&&users.size()>0) {
            System.out.println(users.size()+"===="+pageNo+"====="+users);
            PageData<User> userPageData = new PageData<User>(users.size(), pageNo, pageSize, users);
            if (pageNo>userPageData.getTotalPageCount())
                pageNo = userPageData.getTotalPageCount();
            users = this.userService.getByPage(pageSize,pageNo);
            ActionContext.getContext().put("users",users);
            ActionContext.getContext().put("userPageData",userPageData);
        }
        return "bsuserList";
    }

    @Action("/bsDel")
    @Privilege("system")
    @SkipValidation
    public String del() throws Exception{
        System.out.println(model.getId()+"==============model.getId()===============");
        if (model.getId()!=null)
            this.userService.del(model.getId());
        if (allIDCheck!=null){
            System.out.println(allIDCheck+"============allIDCheck==================");
            String[] allIds = allIDCheck.split(",");
            Long[] ids = new Long[allIds.length];
            for (int i = 0;i<allIds.length;i++){
                String str = allIds[i];
                ids[i] = Long.parseLong(str);
            }
            this.userService.delIds(ids);
        }
//            this.userService.del(allIDCheck);
        return "bsDel";
    }

    @Action("/bsEditUser")
    @Privilege("system")
    @SkipValidation
    public String bsEditUser() throws Exception{
        if (model.getId()!=null){
            System.out.println(model.getId()+"=============");
            model = this.userService.getById(model.getId());
            ActionContext.getContext().put("user",model);
            ServletActionContext.getContext().getValueStack().push(model);
        }
        return "bsEditUser";
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getPrivilegeName() {
        return privilegeName;
    }

    public void setPrivilegeName(String privilegeName) {
        this.privilegeName = privilegeName;
    }

    public String getSecurityCode() {
        return securityCode;
    }

    public void setSecurityCode(String securityCode) {
        this.securityCode = securityCode;
    }

    public String getIsAutoLogin() {
        return isAutoLogin;
    }

    public void setIsAutoLogin(String isAutoLogin) {
        this.isAutoLogin = isAutoLogin;
    }

    public String getAllIDCheck() {
        return allIDCheck;
    }

    public void setAllIDCheck(String allIDCheck) {
        this.allIDCheck = allIDCheck;
    }
}
